<?php

namespace Home\Controller;

use Think\Controller;

/**
 * @desc 默认页面
 * @author 张云江
 */
class IndexController extends Controller
{

    /**
     * 登录页面
     */
    public function index()
    {
        $this->display();
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        //删除cookie
        cookie('order_uid', null);
        cookie('order_login_name', null);
        cookie('order_nick_name', null);
        cookie('order_login_time', null);

        $this->redirect("Index/index");
    }

    /**
     * 【方法】登录验证
     */
    public function m_login()
    {
        $username = I('post.username');
        $password = I('post.password');

        if (empty($username)) {
            $rtn = C('AJAX_RETURN_DATA');
            $rtn['code'] = -1;
            $rtn['notice'] = "用户登陆失败";
            $this->ajaxReturn($rtn);
            return;
        }

        $MemAuth_User = new \Mem\MemAuth_User();
        $info = $MemAuth_User->getInfoWithLogin($username, $password);

        if (empty($info)) {
            $rtn = C('AJAX_RETURN_DATA');
            $rtn['code'] = -1;
            $rtn['notice'] = "用户登陆失败";
            $this->ajaxReturn($rtn);
        } else {
            cookie('order_uid', $info['uid']);
            cookie('order_login_name', $info['login_name']);
            cookie('order_nick_name', $info['nick_name']);
            cookie('order_login_time', date("Y-m-d H:i:s", time()));

            $rtn = C('AJAX_RETURN_DATA');
            $rtn['code'] = 0;
            $rtn['url'] = "application/appmgr.html";

            $this->ajaxReturn($rtn);
        }
    }
    /**
     * 添加应用
     */
    public function m_modifypassword()
    {
        $rtn = array('code' => -1, "notice" => "修改密码失败");

        $old_password = $_POST['old_password'];
        $new_password = $_POST['new_password'];
        $order_uid = $_COOKIE['order_uid'];
        $username = $_COOKIE['order_login_name'];

        $MemAuth_User = new \Mem\MemAuth_User();
        $info = $MemAuth_User->getInfoWithLogin($username, $old_password);
        if (empty($info)) {
            $rtn = array('code' => -1, "notice" => "密码校验失败");
            $this->ajaxReturn($rtn);
        } else {
            $res = $MemAuth_User->updateDataWithLogin_pwd($order_uid, $new_password);
            if ($res) {
                $rtn = array('code' => 0, "notice" => "修改密码成功");
            }
            $this->ajaxReturn($rtn);
        }
    }

    /**
     * 接收苹果订阅返回数据
     */
    public function appleVerify()
    {
        $rtn = array('code' => 0, "notice" => "接收成功");

        if (empty($_POST)) {
            $content = file_get_contents('php://input');
            $post    = (array)json_decode($content, true);
        } else {
            $post = $_POST;
        }

        \Mlog::info('苹果订阅返回数据 = ' . json_encode($post, JSON_UNESCAPED_UNICODE));

        $MemOrder_info = new \Mem\MemOrder_info();
        $MemOrder_info_meta = new \Mem\MemOrder_info_meta();
        $MemOrder_Subscribe_info = new \Mem\MemOrder_Subscribe_info();

        $resultData = $post['unified_receipt'];
        $environment = $post['environment'];
        $build_id = $post['bid'];

        $MemOrder_Application_info = new \Mem\MemOrder_Application_info();
        $applictionInfo = $MemOrder_Application_info->getInfoWithbuild_id($build_id);
        if (empty($applictionInfo)) {
            \Mlog::error('该应用未生成build_id：' . $build_id);
            $rtn = array('code' => 0, "notice" => "应用未生成");
            $this->ajaxReturn($rtn);
            return;
        }
        $application_id = $applictionInfo['application_id'];
        $status = $resultData['status'];
        if ($status == 0) {
            //保存UserInfo 最后更新
            $latest_receipt_info = $resultData['latest_receipt_info'];
            $pending_renewal_info = $resultData['pending_renewal_info'];
            //订单列表
            if (!empty($latest_receipt_info)) {
                foreach ($latest_receipt_info as $orderInfo) {
                    if ($environment == "PROD") {
                        $source_type = 0;
                    } else {
                        $source_type = 1;
                    }
                    $purchase_date = date("Y-m-d H:i:s", (float)$orderInfo['purchase_date_ms'] / 1000);
                    $expires_date = date("Y-m-d H:i:s", (float)$orderInfo['expires_date_ms'] / 1000);
                    $product_id = $orderInfo['product_id'];
                    $transaction_id = $orderInfo['transaction_id'];
                    $cancellation_date = $orderInfo['cancellation_date'];
                    if (!empty($cancellation_date)) {
                        \Mlog::error('苹果内购验证 用户已经退订 cancellation_date = ' . $cancellation_date . ' transaction_id = ' . $transaction_id);
                    }
                    $dborderinfo = $MemOrder_info->getInfoWithtransaction_id($transaction_id);
                    unset($orderInfo['purchase_date']);
                    unset($orderInfo['purchase_date_ms']);
                    unset($orderInfo['purchase_date_pst']);
                    unset($orderInfo['expires_date']);
                    unset($orderInfo['expires_date_ms']);
                    unset($orderInfo['expires_date_pst']);
                    unset($orderInfo['original_purchase_date']);
                    unset($orderInfo['original_purchase_date_ms']);
                    unset($orderInfo['original_purchase_date_pst']);
                    unset($orderInfo['product_id']);
                    unset($orderInfo['transaction_id']);
                    unset($orderInfo['original_transaction_id']);
                    if (empty($dborderinfo)) {
                        //不存在 插入
                        $order_id = $MemOrder_info->insertDataWithParam($product_id, $application_id, $transaction_id, $purchase_date, $expires_date, $source_type);
                        if (!empty($order_id)) {
                            //插入扩展字段
                            foreach ($orderInfo as $k1 => $value) {
                                $MemOrder_info_meta->insertDataWithParam($order_id, $k1, $value, '');
                            }
                        }
                    } else {
                        //存在 更新
                        $order_id = $dborderinfo['order_id'];
                        $wheredata = array("order_id" => $order_id);
                        $MemOrder_info_meta->delDataWithList_id($wheredata);
                        foreach ($orderInfo as $k1 => $value) {
                            $MemOrder_info_meta->insertDataWithParam($order_id, $k1, $value, '');
                        }
                    }
                }
            }
            //订阅情况
            if (!empty($pending_renewal_info)) {
                foreach ($pending_renewal_info as $renewalinfo) {
                    $product_id = $renewalinfo['auto_renew_product_id'];
                    $transaction_id = $renewalinfo['original_transaction_id'];
                    $state = $renewalinfo['auto_renew_status'];
                    $expiration_intent = $renewalinfo['expiration_intent'];
                    $dbsubscribeinfo = $MemOrder_Subscribe_info->getInfoWithtransaction_id($transaction_id);
                    if (empty($dbsubscribeinfo)) {
                        $MemOrder_Subscribe_info->insertDataWithParam($product_id, $application_id, $transaction_id, $state, $expiration_intent);
                    } else {
                        $subscribe_id = $dbsubscribeinfo['subscribe_id'];
                        $upData = array(
                            "product_id" => $product_id,
                            "state" => $state,
                            "expiration_intent" => $expiration_intent,
                        );
                        $wheredata = array(
                            'subscribe_id' => $subscribe_id
                        );
                        $MemOrder_Subscribe_info->updateDataWithParam($upData, $wheredata);
                    }
                }
            }
        } else {
            \Mlog::error('苹果返回数据验证失败status = ' . $resultData['status'] . ' build_id = ' . $build_id);
        }

        //处理通知消息存储
        $MemOrder_Notice_info = new \Mem\MemOrder_Notice_info();
        $product_id = $post['auto_renew_product_id'];
        $notification_type = $post['notification_type'];
        $auto_renew_status = 0;
        $auto_renew_status_s = $post['auto_renew_status'];
        if ($auto_renew_status_s == 'ture') {
            $auto_renew_status = 1;
        }
        $MemOrder_Notice_info->insertDataWithParam($product_id, $build_id, $environment, $notification_type, $auto_renew_status);

        $this->ajaxReturn($rtn);
    }
}
